<template>
    <div id="contract_list">
        <!-- <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 基础表格 </el-breadcrumb-item>
            </el-breadcrumb>
        </div> -->
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" class="handle-del mr10" @click="handleAdd">ADD</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column prop="code" label="code" width="auto" align="center"></el-table-column>

                <el-table-column label="CP名称" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.cppartner ? scope.row.cppartner.name : '' }}</template>
                </el-table-column>

                <el-table-column label="合同开始时间" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.contractStart }}</template>
                </el-table-column>

                <el-table-column label="合同结束时间" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.contractEnd }}</template>
                </el-table-column>

                <el-table-column label="状态" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.status == 0 ? '不可用' : '可用' }}</template>
                </el-table-column>

                <el-table-column label="操作者" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.updateBy }}</template>
                </el-table-column>

                <el-table-column label="更新时间" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.updateTime }}</template>
                </el-table-column>

                <el-table-column label="操作" width="auto" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" @click="handleEdit(scope.$index, scope.row)" size="mini">
                            <!-- 编辑 -->
                            {{ $t('m.editBtn') }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total,sizes, prev, pager, next, jumper"
                    :page-sizes="[5, 10, 20, 30]"
                    @size-change="handleSizeChange"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑合同" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="100px">
                <el-form-item label="合同编号">
                    <el-input class="w" v-model="form.code" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="cp名称">
                    <el-select v-model="form.cpid" class="handle-select mr10 w" clearable>
                        <el-option v-for="(item, index) in cpList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="可用渠道">
                    <el-select v-model="form.channel" class="handle-select mr10 w" clearable multiple>
                        <el-option v-for="(item, index) in channelList" :key="index" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="终端系统">
                    <el-select v-model="form.terminalSystem" class="handle-select mr10 w" clearable multiple>
                        <el-option key="1" label="通用" value="1"></el-option>
                        <el-option key="2" label="OPPO ColorOS系统" value="2"></el-option>
                        <el-option key="3" label="小米MIUI 系统" value="3"></el-option>
                        <el-option key="4" label="vivo OriginOS/FuntouchOS系统" value="4"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="品牌名称">
                    <el-select multiple v-model="form.brands" class="handle-select mr10 w" clearable>
                        <el-option key="0" label="通用" value="1"></el-option>
                        <el-option key="1" label="OPPO" value="2"></el-option>
                        <el-option key="2" label="一加" value="3"></el-option>
                        <el-option key="3" label="realme" value="4"></el-option>
                        <el-option key="4" label="Heytap" value="5"></el-option>
                        <el-option key="5" label="vivo" value="6"></el-option>
                        <el-option key="6" label="iQOO" value="7"></el-option>
                        <el-option key="7" label="NEX" value="8"></el-option>
                        <el-option key="8" label="小米" value="9"></el-option>
                        <el-option key="9" label="红米" value="10"></el-option>
                        <el-option key="10" label="黑鲨" value="11"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="授权场景">
                    <el-select v-model="form.licensingScenarios" class="handle-select mr10 w" clearable multiple>
                        <el-option key="0" label="通用" value="1"></el-option>
                        <el-option key="1" label="流媒体" value="2"></el-option>
                        <el-option key="2" label="K歌" value="3"></el-option>
                        <el-option key="3" label="直播" value="4"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="授权类型">
                    <el-select v-model="form.authorizationType" class="handle-select mr10 w" clearable multiple>
                        <el-option key="1" label="买断" value="1"></el-option>
                        <el-option key="2" label="纯分成" value="2"></el-option>
                        <el-option key="3" label="保底+分成" value="3"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="终端类型">
                    <el-select v-model="form.terminals" class="handle-select mr10 w" clearable multiple>
                        <el-option
                            v-for="(item, index) in terminalList"
                            :key="index"
                            :label="item[index]"
                            :value="index.toString()"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="合同截止日期">
                    <el-date-picker
                        class="w"
                        v-model="form.contractStartEndDate"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    >
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新增弹出框 -->
        <el-dialog title="新增合同" :visible.sync="addVisible" width="30%">
            <el-form ref="form" :model="form" label-width="100px">
                <el-form-item label="cp名称">
                    <el-select v-model="form.cpid" class="handle-select mr10 w" clearable>
                        <el-option v-for="(item, index) in cpList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="可用渠道">
                    <el-select multiple v-model="form.channel" class="handle-select mr10 w" clearable>
                        <el-option v-for="(item, index) in channelList" :key="index" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="终端系统">
                    <el-select multiple v-model="form.terminalSystem" class="handle-select mr10 w" clearable>
                        <el-option key="1" label="通用" value="1"></el-option>
                        <el-option key="2" label="OPPO ColorOS系统" value="2"></el-option>
                        <el-option key="3" label="小米MIUI 系统" value="3"></el-option>
                        <el-option key="4" label="vivo OriginOS/FuntouchOS系统" value="4"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="品牌名称">
                    <el-select multiple v-model="form.brands" class="handle-select mr10 w" clearable>
                        <el-option key="0" label="通用" value="1"></el-option>
                        <el-option key="1" label="OPPO" value="2"></el-option>
                        <el-option key="2" label="一加" value="3"></el-option>
                        <el-option key="3" label="realme" value="4"></el-option>
                        <el-option key="4" label="Heytap" value="5"></el-option>
                        <el-option key="5" label="vivo" value="6"></el-option>
                        <el-option key="6" label="iQOO" value="7"></el-option>
                        <el-option key="7" label="NEX" value="8"></el-option>
                        <el-option key="8" label="小米" value="9"></el-option>
                        <el-option key="9" label="红米" value="10"></el-option>
                        <el-option key="10" label="黑鲨" value="11"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="授权场景">
                    <el-select multiple v-model="form.licensingScenarios" class="handle-select mr10 w" clearable>
                        <el-option key="0" label="通用" value="1"></el-option>
                        <el-option key="1" label="流媒体" value="2"></el-option>
                        <el-option key="2" label="K歌" value="3"></el-option>
                        <el-option key="3" label="直播" value="4"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="授权类型">
                    <el-select v-model="form.authorizationType" class="handle-select mr10 w" clearable multiple>
                        <el-option key="1" label="买断" value="1"></el-option>
                        <el-option key="2" label="纯分成" value="2"></el-option>
                        <el-option key="3" label="保底+分成" value="3"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="终端类型">
                    <el-select multiple v-model="form.terminals" class="handle-select mr10 w" clearable>
                        <el-option
                            v-for="(item, index) in terminalList"
                            :key="index"
                            :label="item[index]"
                            :value="index.toString()"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="合同截止日期">
                    <el-date-picker
                        class="w"
                        v-model="form.contractStartEndDate"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    >
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
  import { debounce, throttle } from '@/utils/utils.js';
  export default {
      name: 'ContractList',
      data() {
          return {
              query: {
                  pageIndex: 1,
                  pageSize: 10
              },
              tableData: [],
              addVisible: false,
              editVisible: false,
              pageTotal: 0,
              form: {
                  cpid: null,
                  channel: null,
                  brands: null,
                  terminalSystem: null,
                  licensingScenarios: null,
                  authorizationType: null,
                  terminals: null,
                  contractStartEndDate: null
              },

              cpList: [],
              channelList: [],
              terminalList: []
          };
      },
      created() {
          this.getData();
      },
      watch: {
          editVisible(a, b) {
              if (a == false) {
                  this.form = {
                      cpid: null,
                      channel: null,
                      brands: null,
                      terminalSystem: null,
                      licensingScenarios: null,
                      authorizationType: null,
                      terminals: null,
                      contractStartEndDate: null
                  };
              }
          },
          addVisible(a, b) {
              if (a == false) {
                  this.form = {
                      cpid: null,
                      channel: null,
                      brands: null,
                      terminalSystem: null,
                      licensingScenarios: null,
                      authorizationType: null,
                      terminals: null,
                      contractStartEndDate: null
                  };
              }
          }
      },
      methods: {
          async getData() {
              try {
                  let url = '/contracts/list';
                  let headers = {};
                  if (localStorage.getItem('roles') && JSON.parse(localStorage.getItem('roles')).includes('CPOA')) {
                      headers['cppname'] = encodeURIComponent(localStorage.getItem('ms_username'));
                  }
                  let { data: res } = await this.$http[0].get(url, {
                      params: this.$removeField({
                          page: this.query.pageIndex,
                          size: this.query.pageSize
                      }),
                      headers
                  });
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  console.log(res);
                  if (res.data.content && res.data.content.length > 0) {
                      res.data.content.map((item) => {
                          item.updateTime = this.$dateFormat(item.updateTime, 'yyyy-mm-dd', '-');
                          item.contractStart = this.$dateFormat(item.contractStart, 'yyyy-mm-dd', '-');
                          item.contractEnd = this.$dateFormat(item.contractEnd, 'yyyy-mm-dd', '-');
                      });
                      this.tableData = res.data.content;
                      this.pageTotal = res.data.totalElements;
                  } else {
                      this.tableData = [];
                      this.pageTotal = 0;
                  }
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          // 触发搜索按钮
          // handleSearch() {
          //     this.$set(this.query, 'pageIndex', 1);
          //     this.getData();
          // },

          handleSearch: debounce(function () {
              this.$set(this.query, 'pageIndex', 1);
              this.getData();
          }, 300),

          // 删除操作
          handleDelete(index, row) {
              // 二次确认删除
              this.$confirm('确定要删除吗？', '提示', {
                  type: 'warning'
              })
                  .then(() => {
                      this.$message.success('删除成功');
                      this.tableData.splice(index, 1);
                  })
                  .catch(() => {});
          },
          // 多选操作
          handleSelectionChange(val) {
              this.multipleSelection = val;
          },
          handleAdd() {
              this.addVisible = true;
              this.getCpList();
              this.getChannelList();
              this.getTerminalList();
          },
          async getTerminalList(resolve) {
              try {
                  let url = '/channel/getTerminal';
                  let { data: res } = await this.$http[4].get(url, {});
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }

                  if (res.data && res.data.length > 0) {
                      this.terminalList = res.data;
                  } else {
                      this.terminalList = [];
                  }
                  resolve && resolve();
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          async getChannelList() {
              try {
                  let url = '/channel/query';
                  let { data: res } = await this.$http[4].get(url, {});
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }

                  if (res.data && res.data.length > 0) {
                      this.channelList = res.data;
                  } else {
                      this.channelList = [];
                  }
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          async getCpList() {
              try {
                  let url = '/contracts/cpps';
                  let { data: res } = await this.$http[0].get(url, {});
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  if (res.data && res.data.length > 0) {
                      this.cpList = res.data;
                  } else {
                      this.cpList = [];
                  }
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          // 编辑操作
          handleEdit(index, row) {
              // this.idx = index;
              // this.form = row;
              this.editVisible = true;

              this.initSelect().then(() => {
                  this.getDataById(row.id);
              });
          },

          initSelect() {
              return new Promise((resolve, reject) => {
                  this.getCpList();
                  this.getChannelList();
                  this.getTerminalList(resolve);
              });
          },
          async getDataById(id) {
              try {
                  let url = '/contracts/detail';
                  let { data: res } = await this.$http[0].get(url, {
                      params: this.$removeField({
                          id
                      })
                  });
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  this.form = {
                      code: res.data.code,
                      id: res.data.id,
                      cpid: res.data.cppId,
                      channel: res.data.channels,
                      brands: res.data.brands,
                      terminalSystem: res.data.terminalSystem,
                      licensingScenarios: res.data.licensingScenarios,
                      authorizationType: res.data.authorizationType,
                      terminals: res.data.terminals,
                      contractStartEndDate: [
                          this.$timstampToStandardDate(res.data.contractStart),
                          this.$timstampToStandardDate(res.data.contractEnd)
                      ]
                  };
                  console.log(res);
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          async saveAdd() {
              try {
                  let url = '/contracts/create';
                  let { data: res } = await this.$http[0].post(
                      url,
                      this.$objTostring(
                          this.$removeField({
                              channel: this.form.channel,
                              brands: this.form.brands,
                              terminalSystem: this.form.terminalSystem,
                              licensingScenarios: this.form.licensingScenarios,
                              authorizationType: this.form.authorizationType,
                              terminals: this.form.terminals,
                              contractStart: this.form.contractStartEndDate
                                  ? this.$dateFormat(this.$standardDateToTimstamp(this.form.contractStartEndDate[0]))
                                  : null,
                              contractEnd: this.form.contractStartEndDate
                                  ? this.$dateFormat(this.$standardDateToTimstamp(this.form.contractStartEndDate[1]))
                                  : null,
                              cppartnerId: this.form.cpid
                          })
                      ),
                      {
                          headers: {
                              'Content-Type': 'application/x-www-form-urlencoded'
                          }
                      }
                  );
                  console.log(res);
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  this.addVisible = false;
                  this.$message.success(res.message);
                  this.form = {
                      cpid: null,
                      channel: null,
                      brands: null,
                      terminalSystem: null,
                      licensingScenarios: null,
                      authorizationType: null,
                      terminals: null,
                      contractStartEndDate: null
                  };
                  this.getData();
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          // 保存编辑
          async saveEdit() {
              try {
                  let url = '/contracts/update';
                  let { data: res } = await this.$http[0].post(
                      url,
                      this.$objTostring(
                          this.$removeField({
                              contractsId: this.form.id,
                              channel: this.form.channel,
                              brands: this.form.brands,
                              terminalSystem: this.form.terminalSystem,
                              licensingScenarios: this.form.licensingScenarios,
                              authorizationType: this.form.authorizationType,
                              terminals: this.form.terminals,
                              contractStart: this.form.contractStartEndDate
                                  ? this.$dateFormat(this.$standardDateToTimstamp(this.form.contractStartEndDate[0]))
                                  : null,
                              contractEnd: this.form.contractStartEndDate
                                  ? this.$dateFormat(this.$standardDateToTimstamp(this.form.contractStartEndDate[1]))
                                  : null,
                              cppartnerId: this.form.cpid
                          })
                      ),
                      {
                          headers: {
                              'Content-Type': 'application/x-www-form-urlencoded'
                          }
                      }
                  );
                  console.log(res);
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  this.editVisible = false;
                  this.$message.success(res.message);
                  this.form = {
                      cpid: null,
                      channel: null,
                      brands: null,
                      terminalSystem: null,
                      licensingScenarios: null,
                      authorizationType: null,
                      terminals: null,
                      contractStartEndDate: null
                  };
                  this.getData();
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          // 分页导航
          handlePageChange(val) {
              this.$set(this.query, 'pageIndex', val);
              this.getData();
          },
          handleSizeChange(val) {
              this.$set(this.query, 'pageSize', val);
              this.getData();
          }
      }
  };
</script>

<style lang="scss">
  #contract_list {
      .table-header {
          .cell {
              white-space: nowrap !important;
          }
      }
      .w {
          width: 100% !important;
      }
      .handle-box {
          margin-bottom: 20px;
      }

      .handle-select {
          width: 120px;
      }

      .handle-input {
          width: 300px;
          display: inline-block;
      }
      .table {
          width: 100%;
          font-size: 14px;
      }
      .red {
          color: #ff0000;
      }
      .mr10 {
          margin-right: 10px;
      }
      .table-td-thumb {
          display: block;
          margin: auto;
          width: 40px;
          height: 40px;
      }
  }
</style>
